package com.tree.shardingjdbc.demo.config;

import com.zaxxer.hikari.HikariDataSource;
import io.shardingsphere.shardingjdbc.api.ShardingDataSourceFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName com.tree.shardingjdbc.demo.config
 * Description: <类功能描述>. <br>
 * <p>
 * 配置数据源详细信息
 * </p>
 * @Author tree
 * @Date 2019-06-02 23:43
 * @Version 1.0
 */
@Configuration
@EnableConfigurationProperties(value = {ShardingMasterSlaveConfig.class})
//@ConditionalOnProperty({ "sharding.jdbc.data-sources.ds_master.jdbc-url",
//        "sharding.jdbc.sharding-rule-config.master-data-source-name" })
public class ShardingDataSourceConfig {
    @Autowired
    private ShardingMasterSlaveConfig shardingMasterSlaveConfig;

    @Bean("dataSource")
    public DataSource masterSlaveDataSource() throws SQLException {
        shardingMasterSlaveConfig.getDataSources().forEach((k,v)->configDataSource(v));
        Map<String,DataSource> dataSourceMap = new HashMap<>();
        dataSourceMap.putAll(shardingMasterSlaveConfig.getDataSources());
        DataSource dataSource = ShardingDataSourceFactory.createDataSource(dataSourceMap,
                shardingMasterSlaveConfig.getShardingRuleConfiguration(),new HashMap<>(),null);
        System.err.println("=========masterSlaveDataSource config complete！！" );
        return dataSource;

    }

    private void configDataSource(HikariDataSource dataSource) {
        dataSource.setMaximumPoolSize(20);
        dataSource.setMinimumIdle(5);
    }
}
